package com.zhanvie.test;

import java.util.HashMap;
import java.util.Map;

public class MapDemo {

    public static void main(String[] args) {
        testComputeIfPresent();
    }

    /**
     * 有则覆盖, 没有就忽略
     */
    public static void testComputeIfPresent() {
        Map<Integer, String> map = new HashMap<>();
        map.put(50, "low-50");
        String s1 = map.computeIfPresent(50, MapDemo::calc);
        String s2 = map.computeIfPresent(70, MapDemo::calc);
        System.out.println(s1);
        System.out.println(s2);
    }

    /**
     * 没有就添加, 有则忽略
     */
    public static void testComputeIfAbsent() {
        Map<Integer, String> map = new HashMap<>();
        map.put(50, "low-50");
        String s1 = map.computeIfAbsent(70, MapDemo::calc);
        String s2 = map.computeIfAbsent(101, MapDemo::calc);
        String s3 = map.computeIfAbsent(50, MapDemo::calc);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }

    private static String calc(int k, String v) {
        k = k+1;
        if (k > 0 && k <= 100) {
            return "low-new-" + k;
        } else if (k > 100 && k < 1000) {
            return "middle-new-" + k;
        } else {
            return "high-new-" + k;
        }
    }

    private static String calc(int k) {
        if (k > 0 && k <= 100) {
            return "low-new-" + k;
        } else if (k > 100 && k < 1000) {
            return "middle-new-" + k;
        } else {
            return "high-new-" + k;
        }
    }

}
